package cn.byapps.attendance.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.byapps.attendance.entity.Ad;
import cn.byapps.attendance.service.AdService;
import cn.byapps.attendance.util.SSLHttpClientUtil;

@Controller
@RequestMapping("/wechat/rest/v1")
public class RestController {


	@Resource
	private AdService adService;

	@Value("${server.url}")
	private String serviceAddress;


	/**
	 * 获取广告信息
	 * 
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/ad")
	@ResponseBody
	public List<Ad> getAd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		List<Ad> ads = adService.listAll();
		String basePath = serviceAddress + req.getContextPath();
		for (Ad ad : ads) {
			ad.setPath(basePath + ad.getPath());
		}
		return ads;
	}

	/**
	 * 天气API
	 * @return
	 */
	@RequestMapping(value = "weather", method = RequestMethod.POST)
	@ResponseBody
	public String getweather(String city) {
		System.out.println(city);
		try {
			System.out.println(URLEncoder.encode(city, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String url = "https://www.sojson.com/open/api/weather/json.shtml?city=%E5%B9%BF%E5%B7%9E";
		String encode = "utf-8";
		String json = "{}";
		try {
			json = SSLHttpClientUtil.get(url, null, encode);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}
}
